<template>
  <div>
      <auth-tag  tips="无权访问">
        <!-- <div class="edit-title-view"><div class="name">批量编辑地块</div> <i @click="onClose" title="关闭" class="vxe-icon-close"></i> </div> -->
        <vxe-toolbar>
          <template #buttons>
            <el-form  :model="form" :inline="true" label-width="80px">
                  <el-form-item label="地块标签" style="width: 100%;">
                    <el-checkbox-group v-model="form.landTagId" style="align-items: center;display: flex;">
                      <el-checkbox v-for="item in landTagsList" :label="item.landTagId">{{item.tagName}}</el-checkbox>
                    </el-checkbox-group> 
                  </el-form-item> 
                  <el-form-item label="地块地质" style="width: 100%;">
                    <el-radio-group v-model="form.geologyId">
                      <el-radio :label="''">全部</el-radio>
                      <el-radio v-for="item in geologyList" :label="item.geologyId">{{item.geologyName}}</el-radio> 
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="地块分组">
                    <el-select v-model="form.landGroupId" clearable placeholder="全部">
                      <el-option 
                        v-for="item in landGroup"
                        :key="item.landGroupId"
                        :label="item.groupName"
                        :value="item.landGroupId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="地块类型">
                    <el-select v-model="form.landTypeId" clearable placeholder="全部">
                      <el-option
                        v-for="item in landType"
                        :key="item.landTypeId"
                        :label="item.landTypeName"
                        :value="item.landTypeId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="作物" label-width="40px">
                    <el-select v-model="form.cropId" clearable placeholder="全部">
                      <el-option
                        v-for="item in cropList" 
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="地块名称">
                    <el-input v-model="form.farmLandName" placeholder="请输入" clearable></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" class="vxe-icon-search" @click="onQuery">查询</el-button>
                  </el-form-item>
            </el-form>
            <div class="btn-hand">
              <el-button type="primary" :disabled="disabledStatus" @click="btnOpen(1,'批量修改分组')" class="vxe-icon-envelope">批量分组</el-button>
              <el-button type="primary" :disabled="disabledStatus" @click="btnOpen(2,'批量修改标签')" class="vxe-icon-file-txt">批量标签</el-button>
              <el-button type="primary" :disabled="disabledStatus" @click="btnOpen(3,'批量修改类型')" class="vxe-icon-folder-open">批量类型</el-button>
              <el-button type="primary" :disabled="disabledStatus" @click="btnOpen(4,'批量修改权属')" class="vxe-icon-flag">批量权属</el-button>
              <el-button type="primary" :disabled="disabledStatus" @click="btnOpen(5,'批量修改质地')" class="vxe-icon-send">批量质地</el-button>
            </div>
          </template>
       </vxe-toolbar>
        <div class="addbox-container">
          <vxe-table 
             ref="refTable"
            :border="true"
            :loading="loading"
             height="auto"
            :row-config="{isHover: true}"
            :column-config="{resizable: true}"
            :scroll-y="{enabled: true}"
            :data="tableData">
            <vxe-column type="checkbox" align="center" title="全选" width="80"></vxe-column>
            <vxe-column field="farmLandNo" title="编号" width="100"></vxe-column>
            <vxe-column field="farmLandName" title="名称" width="240">
              <template #default="{row}">
                <el-input v-model="row.farmLandName" @change="changeLand(row)" @focus="changeLandName(row.farmLandName)" placeholder="名称" />
              </template>
            </vxe-column>
            <vxe-column field="mapAreaSize" title="面积(亩)" width="80"></vxe-column>
            <vxe-column field="locationAddress" title="位置" width="240"> </vxe-column>
            <vxe-column field="landGroupId" title="分组">
              <template #header>
                分组  
                <vxe-icon name="add" title="添加" @click="btnAdd(1,'分组')"  class="btn-add"></vxe-icon>
              </template>
              <template #default="{row}">
                <el-select v-model="row.landGroupId" @change="changeLand(row)" clearable placeholder="请选择">
                  <el-option  row.groupName
                        v-for="item in getGroupNameList(row)" 
                        :key="item.landGroupId"
                        :label="item.groupName"
                        :value="item.landGroupId">
                      </el-option>
                </el-select>
              </template>
            </vxe-column>
            <vxe-column field="landTypeId" title="地块类型">
              <template #default="{row}">
                <el-select v-model="row.landTypeId" @change="changeLand(row)" clearable placeholder="请选择">
                  <el-option
                        v-for="item in landType"
                        :key="item.landTypeId"
                        :label="item.landTypeName" 
                        :value="item.landTypeId">
                      </el-option> 
                </el-select>
              </template>
            </vxe-column>
            <vxe-column field="geologyId" title="土壤地质">
              <template #default="{row}">
                <el-select v-model="row.geologyId" @change="changeLand(row)" clearable placeholder="请选择">
                  <el-option
                    v-for="item in geologyList"
                    :key="item.geologyId" 
                    :label="item.geologyName"
                    :value="item.geologyId">
                  </el-option>
                </el-select>
              </template>
            </vxe-column>
            <vxe-column field="landBelongId">
              <template #header>
                地块权属
                <vxe-icon name="add" title="添加" @click="btnAdd(2,'地块权属')"  class="btn-add"></vxe-icon>
              </template>
              <template #default="{row}"> 
                <el-select v-model="row.landBelongId" @change="changeLand(row)" clearable placeholder="请选择">
                  <el-option
                    v-for="item in belongList" 
                    :key="item.landBelongId"  
                    :label="item.landBelongName" 
                    :value="item.landBelongId">
                  </el-option>
                </el-select>
              </template>
            </vxe-column>
            <vxe-column field="tagsName">
              <template #header>
                地块标签  
                <vxe-icon name="add" title="添加" @click="btnAdd(3,'地块标签')"  class="btn-add"></vxe-icon>
              </template>
              <template #default="{row}">
                <template v-if="row.tagsName">
                  <el-tag effect="dark" type="success" style="margin-right:5px;margin-bottom:5px;" v-for="item in row.tagsName.split(',')">{{item}}</el-tag>
                </template>
                </template>
            </vxe-column>

          </vxe-table>
        </div>
        <vxe-pager
          background
          v-model:current-page="page"
          @page-change="changePage"
          v-model:page-size="limit"
          :total="total"
          :page-sizes="[10, 20,120,200,300,500,1000]"
          :layouts="['Total','PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump']">
        </vxe-pager>
      </auth-tag>
  
    <vxe-modal v-model="modalType" :title="modalTitle" width="400" show-footer>
      <template #default>
        <el-form  :model="updateFrom" v-if="modalType" label-width="80px" style="padding-top:10px;">
                  <el-form-item :label="modalTitle.replace('批量修改','地块')">
                    <el-select v-model="updateFrom.updateIds" :multiple="selectType==2" clearable placeholder="请选择">
                      <el-option
                        v-for="item in getSelectData"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
            </el-form>
      </template>
      <template #footer>
        <el-button class="vxe-icon-close" @click="modalType=false">关闭</el-button>
            <el-button type="primary" class="vxe-icon-check" :loading="LoadingSave" @click="onSubmit">保存</el-button>
        </template>
    </vxe-modal>
    <vxe-modal ref="modalAdd" v-model="modalAddType" :title="'添加'+modalTitle" width="400" @zoom="zoomBox" show-zoom resize show-footer>
      <template #default>
        <el-form  :model="form" style="padding-top:10px;">
            <el-form-item :label="modalTitle">
              <el-input :placeholder="'请输入'+modalTitle" clearable v-model="addText"><template #append> <span @click="saveSelect" style="cursor: pointer;">添加</span></template></el-input>
            </el-form-item>
        </el-form>
        <vxe-table
            ref="refTable"
            :border="true"
            :height="tableHeight"
            :row-config="{isHover: true}"
            :column-config="{resizable: true}"
            :scroll-y="{enabled: true}"
            :data="getMinTableList">
            <vxe-column type="seq" title="序号" width="60"></vxe-column>
            <vxe-column field="name" :title="modalTitle+'名称'"></vxe-column>
            <vxe-column field="id" title="操作"  width="85">
              <template #default="{row}">
                <vxe-button type="text" status="danger" @click="btnDel(row)" content="删除" icon="vxe-icon-delete"></vxe-button>
                </template>
            </vxe-column>
        </vxe-table>
      </template>
      <template #footer>
        <el-button class="vxe-icon-close" @click="modalAddType=false">关闭</el-button>
            <el-button type="primary" class="vxe-icon-check" @click="modalAddType=false">保存</el-button>
        </template>
    </vxe-modal>
</div>
</template>

<script setup name="Factor-Team-List">
import { nextTick, ref, watch, onActivated, reactive, onMounted,computed } from 'vue'
import { useRouter } from 'vue-router'
import mainLayout from '@/components/custom/mainLayout.vue'
import { useUserStore } from '@/pinia/modules/user'
import {VXETable} from 'vxe-table'
import { getUserList,getSelectList} from '@/api/select'
import {
  getLandList,
  getLandGroupList,
  getLandTypeList,
  getGeologyList,
  getBelongList,
  getLandTagsList,
  addGroup,
  delGroup,
  addLandBelong,
  addLandTags,
  deleteBelong,
  editFarmLand,
  deleteTags,
  landUpdateBatch,
  landTagsUpdateBatch
} from '@/api/plant'
const userStore = useUserStore()
const tableData = ref([])
const minTableData = ref([])
const refTable =ref(null)
const modalAdd =ref(null)
const modalType =ref(false)
const modalAddType =ref(false)
const loading =ref(false)
const modalTitle =ref('')
const tableHeight=ref('300px')
const addText =ref('')
const emit = defineEmits(['close'])

const props = defineProps({
  farmLandId:{
        type:String,
        default:''
    }
})

const page = ref(1)
const limit = ref(10)
const total = ref(0)
const LoadingSave = ref(false)
const cropList = ref([])
const landGroup = ref([])
const landType = ref([])
const geologyList = ref([])
const belongList = ref([])
const landTagsList = ref([])
const minType =ref(1)
const selectType =ref(1)
const form = ref({
  landTagId:[],
  geologyId: '',
  landGroupId: '',
  landTypeId: '',
  cropId: '',
  farmLandName: '',
})

const updateFrom = ref({updateIds: ''})
const disabledStatus =computed(()=>{
  let list = refTable?.value?.getCheckboxRecords() ||[ ]
  if(list.length>0){
    return false
  }else{
    return true
  }
})
 
const getMinTableList =computed(()=>{
  if(minType.value==1){
    return  minTableData.value = landGroup.value.map((item)=>{
        return {
          id:item.landGroupId,
          name:item.groupName
        }
      })
  }

  if(minType.value==2){ 
    return minTableData.value = belongList.value.map((item)=>{
        return {
          id:item.landBelongId,
          name:item.landBelongName
        }  
      })
  }  
  if(minType.value==3){
    return  minTableData.value = landTagsList.value.map((item)=>{
        return {
          id:item.landTagId,
          name:item.tagName
        }
      })
  }
})

const getGroupNameList =(row)=>{
  if(landGroup.value && row){
    let list = landGroup.value.filter((item)=>{
       return item.landGroupId== row.landGroupId
    })
    if(list.length==0){
      landGroup.value.push({
        landGroupId:row.landGroupId,
        groupName:row.groupName
      })
    }
   return landGroup.value
  }
}

const getSelectData =computed(()=>{
  if(selectType.value==1){
    return  landGroup.value.map((item)=>{
        return {
          id:item.landGroupId,
          name:item.groupName
        }
      })
  }
  if(selectType.value==2){ 
    return  landTagsList.value.map((item)=>{
        return {
          id:item.landTagId,
          name:item.tagName
        }  
      })
  }    
  if(selectType.value==3){
    return   landType.value.map((item)=>{
        return {
          id:item.landTypeId,
          name:item.landTypeName  
        }
      })
  }
  if(selectType.value==4){ 
    return belongList.value.map((item)=>{
        return {
          id:item.landBelongId,
          name:item.landBelongName
        }  
      })
  }  
  if(selectType.value==5){ 
    return  geologyList.value.map((item)=>{
        return {
          id:item.geologyId,
          name:item.geologyName
        }  
      })
  }  
})


const zoomBox =(e)=>{
  tableHeight.value = (Number(modalAdd.value.getBox().style.height.replace('px',''))-170)+'px'
}

  onMounted(async () => {
      get_land_list()
      cropList.value = await  getSelectList({ page: 1, limit: 100,lovCode:'TANC_CROP'})
      getLandGroup()
      getLandType()
      getGeology()
      getBelong()
      getLandTags()
  })

  //分组
  const getLandGroup =async ()=>{
    let res  = await  getLandGroupList({
       page: 1, 
       limit: 100,
       farmId:userStore.userInfo.farmId,
      companyId:userStore.userInfo.companyId
    })
    if(res.success){
      landGroup.value = res.data ||[]
    }
  }
  //类型
  const getLandType =async ()=>{
    let res  = await  getLandTypeList({page: 1, 
       limit: 100,
      farmId:userStore.userInfo.farmId,
      companyId:userStore.userInfo.companyId})
    if(res.success){
      landType.value = res.data ||[]
    }
  }
  //土壤地质
  const getGeology =async ()=>{
    let res  = await  getGeologyList({ page: 1, 
       limit: 100,
      farmId:userStore.userInfo.farmId,
      companyId:userStore.userInfo.companyId})
    if(res.success){
        geologyList.value = res.data ||[]
    }
  }
    //地块权属
    const getBelong =async ()=>{
    let res  = await  getBelongList({ page: 1, 
       limit: 100,
      farmId:userStore.userInfo.farmId,
      companyId:userStore.userInfo.companyId})
    if(res.success){
      belongList.value = res.data ||[]
    }
  }

    //地块标签
    const getLandTags =async ()=>{
    let res  = await  getLandTagsList({ page: 1, 
       limit: 100,
      farmId:userStore.userInfo.farmId,
      companyId:userStore.userInfo.companyId})
    if(res.success){
      landTagsList.value = res.data ||[]
    }
  }

  
  //地块列表
  const get_land_list = async ()=>{
    loading.value = true
    const res = await getLandList({
        page:page.value,
        limit:limit.value,
        farmLandId:props.farmLandId,
        farmId:userStore.userInfo.farmId,
        companyId:userStore.userInfo.companyId,
        column:"id",
        order:"desc",
        ...form.value
    })
    if(res.success){
        loading.value = false
        tableData.value = res.data
        total.value = res.total
    }else{
      loading.value = false
    }
  }

  const changePage =({currentPage, pageSize})=>{
    page.value = currentPage
    limit.value = pageSize
    get_land_list()
  }
  
const onQuery =()=>{
   page.value= 1
   get_land_list()
}
let landNameText=null
const changeLandName=(val)=>{
  landNameText =val
}
const changeLand =async (row)=>{

  if(landNameText==row.farmLandName){
    return
  }
  let res = await editFarmLand({
    farmLandId:row.farmLandId,
    farmLandName:row.farmLandName,
    landGroupId:row.landGroupId,
    landTypeId:row.landTypeId,
    geologyId:row.geologyId,
    landBelongId:row.landBelongId,
    groupName:landGroup.value.find((item)=>row.landGroupId==item.landGroupId)?.groupName||null,
    geologyName:geologyList.value.find((item)=>row.geologyId==item.geologyId)?.geologyName||null,
    landBelong:belongList.value.find((item)=>row.landBelongId==item.landBelongId)?.landBelongName||null,
  })
  if(res.success){
      VXETable.modal.message({ content: '保存成功', status: 'success'})
    }else{
      VXETable.modal.message({ content: res.message, status: 'error'})
    }
}



const onSubmit=async ()=>{
  let list = refTable?.value?.getCheckboxRecords() ||[ ]
 let pdataList =[]
 LoadingSave.value = true
  list.map((item)=>{
    //分组
    if(selectType.value==1){
      item.landGroupId=updateFrom.value.updateIds
      pdataList.push({
          farmLandId:item.farmLandId,
          groupName:landGroup.value.find((item)=>updateFrom.value.updateIds==item.landGroupId)?.groupName||null,
          landGroupId:updateFrom.value.updateIds,
        })
    }
    //标签
     if(selectType.value==2){
        updateFrom.value.updateIds.forEach(tagId => {
          pdataList.push({
            farmLandId:item.farmLandId,
            landTagId:tagId
          })
        });
    }
   //类型
    if(selectType.value==3){
      item.landTypeId=updateFrom.value.updateIds
      pdataList.push({
          farmLandId:item.farmLandId,
          landTypeId:updateFrom.value.updateIds,
        })
    }
    //权属
    if(selectType.value==4){
        item.landBelongId=updateFrom.value.updateIds
        pdataList.push({
            farmLandId:item.farmLandId,
            landBelongId:updateFrom.value.updateIds,
            landBelong:belongList.value.find((item)=>updateFrom.value.updateIds==item.landBelongId)?.landBelongName||null,
          })
      }
      //质地
    if(selectType.value==5){
        item.geologyId=updateFrom.value.updateIds
        pdataList.push({
            farmLandId:item.farmLandId,
            geologyId:updateFrom.value.updateIds,
            geologyName:geologyList.value.find((item)=>updateFrom.value.updateIds==item.geologyId)?.geologyName||null,
          })
      }
      return item
    })
  let res =selectType.value==2?await landTagsUpdateBatch(pdataList):await landUpdateBatch(pdataList)
  if(res.success){
      VXETable.modal.message({ content: '保存成功', status: 'success'})
      modalType.value = false
      LoadingSave.value = false
      updateFrom.value.updateIds=(selectType.value==2?[]:'')
      get_land_list()
    }else{
      LoadingSave.value = false
      VXETable.modal.message({ content: res.message, status: 'error'})
    }
}

const btnAdd=(type,title)=>{
  modalAddType.value = true
  modalTitle.value = title
  minType.value = type
}
 const btnOpen=(type,title)=>{
    modalType.value = true
    modalTitle.value = title
    selectType.value = type
    updateFrom.value.updateIds=(selectType.value==2?[]:'')
}
const saveSelect=async ()=>{
  if(!addText.value){
    VXETable.modal.message({ content: '名称不能为空', status: 'error'})
    return 
  }
  let res =minType.value==1?await addGroup({farmId:userStore.userInfo.farmId,groupName:addText.value}):
  (
    minType.value==2?await addLandBelong({companyId:userStore.userInfo.companyId,landBelongName:addText.value}):
    await addLandTags({companyId:userStore.userInfo.companyId,tagName:addText.value})
  )
  if(res.success){
      VXETable.modal.message({ content: '新增成功', status: 'success'})
      addText.value=''
      if(minType.value==1){
        getLandGroup()
      }else if(minType.value==2){
        getBelong()
      }else{
        getLandTags()
      }
     
    }else{
      VXETable.modal.message({ content: res.message, status: 'error'})
    }
}

const btnDel=async (row)=>{
  const info = await VXETable.modal.confirm({
        title:'提示',
        content:'您确定要删除该数据?'
    })
    if(info==='confirm'){
      let res = minType.value==1?await delGroup([row.id]):(minType.value==2?await deleteBelong([row.id]):await deleteTags([row.id])) 
        if(res.success){
          VXETable.modal.message({ content: '删除成功', status: 'success'})
          if(minType.value==1){
              getLandGroup()
            }else if(minType.value==2){
              getBelong()
            }else{
              getLandTags()
            }
        }else{
          VXETable.modal.message({ content: res.message, status: 'error'})
        }
    }
}
const onClose = ()=>{
    emit('close')
}

</script>

<style lang="scss" scoped>
.edit-title-view{
  display:flex;
  justify-content: space-between;
  padding:13px 10px;
  border-bottom: 1px solid #ddd;
  background-color: #fff;
  .name{
    font-size:15px;
    font-weight: bold;
  }
  .vxe-icon-close{
    font-size:16px;
    color:#888;
    cursor: pointer;
  }
}
.addbox-container{
  box-sizing: border-box;
  height: calc(100vh - 360px);
  padding:10px;
  background-color: #fff;
}
.el-checkbox{
  --el-checkbox-checked-text-color:#04AE70;
  --el-checkbox-checked-bg-color:#04AE70;
  --el-checkbox-checked-input-border-color:#04AE70;
}

.el-form-item--default{
  margin-bottom: 10px;
}
.btn-add {
  color: #04AE70; font-size: 14px; cursor: pointer;margin-left:6px;
}
.btn-hand{
  display: flex;
  align-items: end;
  padding:10px 10px 0 10px;
}
</style>
